<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>几种实现主题切换的方式 | 小苑の博客</title><meta name="author" content="coderyh"><meta name="copyright" content="coderyh"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="CSS color-scheme 和夜间模式 - 掘金 (juejin.cn)  感知系统的主题切换自动更换主题 prefers-color-schema 是 CSS 媒体特性 @media 中用于检测用户是否将系统的主题色设置为亮色或者暗色。  在 CSS 中使用： 123456789101112131415&#x2F;* Light mode *&#x2F;@media (prefers-color-schem">
<meta property="og:type" content="article">
<meta property="og:title" content="几种实现主题切换的方式">
<meta property="og:url" content="http://localhost:4000/blog/20231225171234/index.html">
<meta property="og:site_name" content="小苑の博客">
<meta property="og:description" content="CSS color-scheme 和夜间模式 - 掘金 (juejin.cn)  感知系统的主题切换自动更换主题 prefers-color-schema 是 CSS 媒体特性 @media 中用于检测用户是否将系统的主题色设置为亮色或者暗色。  在 CSS 中使用： 123456789101112131415&#x2F;* Light mode *&#x2F;@media (prefers-color-schem">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://localhost:8080/image??1703495554000">
<meta property="article:published_time" content="2023-12-25T09:12:34.000Z">
<meta property="article:modified_time" content="2024-01-12T09:05:39.688Z">
<meta property="article:author" content="coderyh">
<meta property="article:tag" content="默认标签">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://localhost:8080/image??1703495554000"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="http://localhost:4000/blog/20231225171234/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"/blog/./search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '几种实现主题切换的方式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-01-12 17:05:39'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 导航</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/navigation/work/"><i class="fa-fw fas fa-coffee"></i><span> 工作</span></a></li><li><a class="site-page child" href="/blog/navigation/moyu/"><i class="fa-fw fas fa-th-list"></i><span> 摸鱼</span></a></li><li><a class="site-page child" href="/blog/navigation/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/navigation/design/"><i class="fa-fw fas fa-pencil-alt"></i><span> 设计</span></a></li><li><a class="site-page child" href="/blog/navigation/resource/"><i class="fa-fw fas fa-book"></i><span> 资源</span></a></li><li><a class="site-page child" href="/blog/navigation/tool/"><i class="fa-fw fas fa-wrench"></i><span> 工具</span></a></li><li><a class="site-page child" href="/blog/navigation/project/"><i class="fa-fw fas fa-project-diagram"></i><span> 项目</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-desktop"></i><span> 软件</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/software/usual/"><i class="fa-fw fas fa-desktop"></i><span> 常用</span></a></li><li><a class="site-page child" href="/blog/software/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/software/open/"><i class="fa-fw fas fa-code-branch"></i><span> 开源</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-compass"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-user"></i><span> 设置</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/pro/"><i class="fa-fw fas fa-user"></i><span> 页面管理</span></a></li><li><a class="site-page child" href="/blog/admin/"><i class="fa-fw fas fa-user"></i><span> 后台管理</span></a></li><li><a class="site-page child" href="/blog/bridge/"><i class="fa-fw fas fa-cog"></i><span> 配置管理</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://localhost:8080/image??1703495554000')"><nav id="nav"><span id="blog-info"><a href="/blog/" title="小苑の博客"><span class="site-name">小苑の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 导航</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/navigation/work/"><i class="fa-fw fas fa-coffee"></i><span> 工作</span></a></li><li><a class="site-page child" href="/blog/navigation/moyu/"><i class="fa-fw fas fa-th-list"></i><span> 摸鱼</span></a></li><li><a class="site-page child" href="/blog/navigation/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/navigation/design/"><i class="fa-fw fas fa-pencil-alt"></i><span> 设计</span></a></li><li><a class="site-page child" href="/blog/navigation/resource/"><i class="fa-fw fas fa-book"></i><span> 资源</span></a></li><li><a class="site-page child" href="/blog/navigation/tool/"><i class="fa-fw fas fa-wrench"></i><span> 工具</span></a></li><li><a class="site-page child" href="/blog/navigation/project/"><i class="fa-fw fas fa-project-diagram"></i><span> 项目</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-desktop"></i><span> 软件</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/software/usual/"><i class="fa-fw fas fa-desktop"></i><span> 常用</span></a></li><li><a class="site-page child" href="/blog/software/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/software/open/"><i class="fa-fw fas fa-code-branch"></i><span> 开源</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-compass"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-user"></i><span> 设置</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/pro/"><i class="fa-fw fas fa-user"></i><span> 页面管理</span></a></li><li><a class="site-page child" href="/blog/admin/"><i class="fa-fw fas fa-user"></i><span> 后台管理</span></a></li><li><a class="site-page child" href="/blog/bridge/"><i class="fa-fw fas fa-cog"></i><span> 配置管理</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">几种实现主题切换的方式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-12-25T09:12:34.000Z" title="发表于 2023-12-25 17:12:34">2023-12-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-01-12T09:05:39.688Z" title="更新于 2024-01-12 17:05:39">2024-01-12</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E9%BB%98%E8%AE%A4%E5%88%86%E7%B1%BB/">默认分类</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">668</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>3分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="几种实现主题切换的方式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7121532248527994893#heading-0">CSS color-scheme 和夜间模式 - 掘金 (juejin.cn)</a></p>
</blockquote>
<h2 id="感知系统的主题切换自动更换主题"><a href="#感知系统的主题切换自动更换主题" class="headerlink" title="感知系统的主题切换自动更换主题"></a>感知系统的主题切换自动更换主题</h2><blockquote>
<p><code>prefers-color-schema</code> 是 CSS 媒体特性 <code>@media</code> 中用于检测用户是否将系统的主题色设置为亮色或者暗色。</p>
</blockquote>
<p>在 CSS 中使用：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Light mode */</span></span><br><span class="line"><span class="keyword">@media</span> (<span class="attribute">prefers-color-scheme</span>: light) &#123;</span><br><span class="line">  <span class="selector-tag">body</span> &#123;</span><br><span class="line">    <span class="attribute">color</span>: black;</span><br><span class="line">    <span class="attribute">background-color</span>: white;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Dark mode */</span></span><br><span class="line"><span class="keyword">@media</span> (<span class="attribute">prefers-color-scheme</span>: dark) &#123;</span><br><span class="line">  <span class="selector-tag">body</span> &#123;</span><br><span class="line">    <span class="attribute">color</span>: white;</span><br><span class="line">    <span class="attribute">background-color</span>: black;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 Link 标签中使用：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Light Mode --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">&quot;stylesheet&quot;</span> <span class="attr">media</span>=<span class="string">&quot;(prefers-color-scheme: dark)&quot;</span><span class="attr">href</span>=<span class="string">&quot;&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Dark Mode --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">&quot;stylesheet&quot;</span> <span class="attr">media</span>=<span class="string">&quot;(prefers-color-scheme: light)&quot;</span> <span class="attr">href</span>=<span class="string">&quot;&quot;</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>获取系统主题色：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取系统主题色</span></span><br><span class="line"><span class="keyword">var</span> isLight = <span class="variable language_">window</span>.<span class="title function_">matchMedia</span>(<span class="string">&#x27;(prefers-color-scheme: light)&#x27;</span>).<span class="property">matches</span>;</span><br><span class="line"><span class="keyword">var</span> isDarkMode = <span class="variable language_">window</span>.<span class="title function_">matchMedia</span>(<span class="string">&#x27;(prefers-color-scheme: dark)&#x27;</span>).<span class="property">matches</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听主题色变化</span></span><br><span class="line"><span class="keyword">const</span> themeMedia = <span class="variable language_">window</span>.<span class="title function_">matchMedia</span>(<span class="string">&quot;(prefers-color-scheme: light)&quot;</span>);</span><br><span class="line">themeMedia.<span class="title function_">addListener</span>(<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (e.<span class="property">matches</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;light&quot;</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;dark&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>



<h2 id="基于原生的CSS变量手动更换主题"><a href="#基于原生的CSS变量手动更换主题" class="headerlink" title="基于原生的CSS变量手动更换主题"></a>基于原生的CSS变量手动更换主题</h2><p>首先我们定义出 <code>Light</code> 主题样式 和 <code>Dark</code> 主题样式</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">// 定义基础色值，方便 UI 后期替换</span><br><span class="line"><span class="selector-pseudo">:root</span> &#123;</span><br><span class="line">    <span class="attr">--zt-c-white</span>: <span class="number">#ffffff</span>;</span><br><span class="line">    <span class="attr">--zt-c-black</span>: <span class="number">#181818</span>;</span><br><span class="line">    <span class="attr">--zt-c-primary</span>: <span class="built_in">rgb</span>(<span class="number">56</span>, <span class="number">173</span>, <span class="number">122</span>);</span><br><span class="line"></span><br><span class="line">    <span class="attr">--zt-c-text-light-1</span>: <span class="number">#333</span>;</span><br><span class="line">    <span class="attr">--zt-c-text-light-2</span>: <span class="number">#666</span>;</span><br><span class="line">    <span class="attr">--zt-c-text-dark-1</span>: <span class="built_in">var</span>(--zt-c-white);</span><br><span class="line">    <span class="attr">--zt-c-text-dark-2</span>: <span class="built_in">rgba</span>(<span class="number">235</span>, <span class="number">235</span>, <span class="number">235</span>, <span class="number">0.64</span>);</span><br><span class="line">&#125;</span><br><span class="line">// Light 默认主题色</span><br><span class="line"><span class="selector-pseudo">:root</span> &#123;</span><br><span class="line">    <span class="attr">--color-background</span>: <span class="built_in">var</span>(--zt-c-white);</span><br><span class="line">    <span class="attr">--color-heading</span>: <span class="built_in">var</span>(--zt-c-primary);</span><br><span class="line">    <span class="attr">--color-text</span>: <span class="built_in">var</span>(--zt-c-text-light-<span class="number">1</span>);</span><br><span class="line">    <span class="attr">--color-text-2</span>: <span class="built_in">var</span>(--zt-c-text-light-<span class="number">2</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// Dark</span><br><span class="line"><span class="selector-pseudo">:root</span> &#123;</span><br><span class="line">    <span class="attr">--color-background</span>: <span class="built_in">var</span>(--zt-c-black);</span><br><span class="line">    <span class="attr">--color-heading</span>: <span class="built_in">var</span>(--zt-c-primary);</span><br><span class="line">    <span class="attr">--color-text</span>: <span class="built_in">var</span>(--zt-c-text-dark-<span class="number">1</span>);</span><br><span class="line">    <span class="attr">--color-text-2</span>: <span class="built_in">var</span>(--zt-c-text-dark-<span class="number">2</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>目前来看，上面的代码是相互覆盖的，我们可以借助 CSS 的优先级来进行区别命中。我们只需要再 body 标签上添加一个自定义属性：<code>theme-mode=&quot;dark&quot;</code>，然后通过这个属性值来匹配不同 <code>tag</code> 的主题色。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">// 上面的代码可以改造成下面这样</span><br><span class="line"><span class="selector-pseudo">:root</span> <span class="selector-tag">body</span><span class="selector-attr">[theme-mode=<span class="string">&quot;dark&quot;</span>]</span> &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 通过JavaScript代码设置主题模式</span><br><span class="line">document<span class="selector-class">.body</span><span class="selector-class">.setAttribute</span>(&quot;theme-mode&quot;, &quot;dark&quot;);</span><br></pre></td></tr></table></figure>

<p>为了视觉上丝滑一点，我们可以给 <code>body</code> 增加点过渡动画</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">    <span class="attribute">min-height</span>: <span class="number">100vh</span>;</span><br><span class="line">    <span class="attribute">color</span>: <span class="built_in">var</span>(--color-text);</span><br><span class="line">    <span class="attribute">background</span>: <span class="built_in">var</span>(--color-background);</span><br><span class="line">    <span class="attribute">transition</span>: color <span class="number">0.5s</span>, background-color <span class="number">0.5s</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<blockquote>
<p>一行代码实现主题切换</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">onclick</span>=<span class="string">&quot;javascript:document.body.setAttribute(&#x27;data-theme&#x27;, document.body.getAttribute(&#x27;data-theme&#x27;) == &#x27;light&#x27; ? &#x27;dark&#x27; : &#x27;light&#x27;)&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">style</span>=<span class="string">&quot;</span></span></span><br><span class="line"><span class="string"><span class="tag">        width: 50px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        height: 50px; </span></span></span><br><span class="line"><span class="string"><span class="tag">        color: rgb(102, 102, 102);</span></span></span><br><span class="line"><span class="string"><span class="tag">        background: white; </span></span></span><br><span class="line"><span class="string"><span class="tag">        border: 1px solid rgb(221, 221, 221); </span></span></span><br><span class="line"><span class="string"><span class="tag">        border-radius: 4px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        line-height: 50px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        text-align: center;</span></span></span><br><span class="line"><span class="string"><span class="tag">        font-size: 1.2rem;</span></span></span><br><span class="line"><span class="string"><span class="tag">        box-shadow: rgb(238, 238, 238) 0px 0px 6px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        position: fixed;</span></span></span><br><span class="line"><span class="string"><span class="tag">        right: 50px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        bottom: 70px;</span></span></span><br><span class="line"><span class="string"><span class="tag">        cursor: pointer;&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">i</span> <span class="attr">class</span>=<span class="string">&quot;fa fa-adjust&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">i</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://localhost:4000/blog">coderyh</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://localhost:4000/blog/20231225171234/">http://localhost:4000/blog/20231225171234/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://localhost:4000/blog" target="_blank">小苑の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/%E9%BB%98%E8%AE%A4%E6%A0%87%E7%AD%BE/">默认标签</a></div><div class="post_share"><div class="social-share" data-image="http://localhost:8080/image??1703495554000" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/20231225185353/" title="Docsify+Themeable主题系统"><img class="cover" src="http://localhost:8080/image?1703501633000" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Docsify+Themeable主题系统</div></div></a></div><div class="next-post pull-right"><a href="/blog/20231211210024/" title="JavaScript系列之循环方式"><img class="cover" src="http://localhost:8080/image?1702299624000" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JavaScript系列之循环方式</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/20240105211227/" title="学习笔记"><img class="cover" src="http://localhost:8080/image?1704460347000" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-05</div><div class="title">学习笔记</div></div></a></div><div><a href="/blog/20240111022327/" title="随机图片接口"><img class="cover" src="http://localhost:8080/image" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-11</div><div class="title">随机图片接口</div></div></a></div><div><a href="/blog/20240105205323/" title="觅思文档使用系列(一)"><img class="cover" src="http://localhost:8080/image?2024-01-05 20:53:23" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-05</div><div class="title">觅思文档使用系列(一)</div></div></a></div><div><a href="/blog/20240105205205/" title="7z系列(一)"><img class="cover" src="http://localhost:8080/image?1704459125000" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-05</div><div class="title">7z系列(一)</div></div></a></div><div><a href="/blog/20240103224501/" title="Win10桌面鼠标右键反应慢"><img class="cover" src="http://localhost:8080/image" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-03</div><div class="title">Win10桌面鼠标右键反应慢</div></div></a></div><div><a href="/blog/20240103214453/" title="将一个程序注册为Windows服务"><img class="cover" src="http://localhost:8080/image?1704289493000" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-03</div><div class="title">将一个程序注册为Windows服务</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%84%9F%E7%9F%A5%E7%B3%BB%E7%BB%9F%E7%9A%84%E4%B8%BB%E9%A2%98%E5%88%87%E6%8D%A2%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%8D%A2%E4%B8%BB%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">感知系统的主题切换自动更换主题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E%E5%8E%9F%E7%94%9F%E7%9A%84CSS%E5%8F%98%E9%87%8F%E6%89%8B%E5%8A%A8%E6%9B%B4%E6%8D%A2%E4%B8%BB%E9%A2%98"><span class="toc-number">2.</span> <span class="toc-text">基于原生的CSS变量手动更换主题</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By coderyh</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">页脚自定义文本</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>(() => {
  const $mermaid = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaid.length === 0) return
  const runMermaid = () => {
    window.loadMermaid = true
    const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

    Array.from($mermaid).forEach((item, index) => {
      const mermaidSrc = item.firstElementChild
      const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
      const mermaidID = 'mermaid-' + index
      const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent

      const renderFn = mermaid.render(mermaidID, mermaidDefinition)

      const renderV10 = () => {
        renderFn.then(({svg}) => {
          mermaidSrc.insertAdjacentHTML('afterend', svg)
        })
      }

      const renderV9 = svg => {
        mermaidSrc.insertAdjacentHTML('afterend', svg)
      }

      typeof renderFn === 'string' ? renderV9(renderFn) : renderV10()
    })
  }

  const loadMermaid = () => {
    window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
  }

  btf.addGlobalFn('themeChange', runMermaid, 'mermaid')

  window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
})()</script><script>(() => {
  const abcjsInit = () => {
    const abcjsFn = () => {
      document.querySelectorAll(".abc-music-sheet").forEach(ele => {
        ABCJS.renderAbc(ele, ele.innerHTML, {responsive: 'resize'})
      })
    }
    
    typeof ABCJS === 'object' ? abcjsFn()
      : getScript('https://cdn.jsdelivr.net/npm/abcjs/dist/abcjs-basic-min.min.js').then(abcjsFn)
  }

  window.pjax ? abcjsInit() : window.addEventListener('load', abcjsInit)
})()</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/blog/js/search/local-search.js"></script></div></div></body></html>